from selenium import webdriver
from time import sleep,time
from selenium.webdriver.support.select import Select
import random

try:
    driver = webdriver.Chrome()
    driver.get('http://localhost/ranzhi/www/sys/user-login.html')
    driver.maximize_window()
    # 隐式等待
    driver.implicitly_wait(10)

    # 登陆
    driver.find_element_by_id('account').send_keys('admin')
    driver.find_element_by_id('password').send_keys('123456')
    driver.find_element_by_id('submit').click()

    # 点击后台管理
    driver.find_element_by_id('s-menu-superadmin').click()

    # 定位iframe元素
    iframe = driver.find_element_by_id('iframe-superadmin')
    # 切换到iframe中
    driver.switch_to.frame(iframe)

    for i in range(16,20):
        # 点击 添加成员
        driver.find_element_by_partial_link_text('添加成员').click()

        # 用户名
        driver.find_element_by_id('account').send_keys('user%d'%i)

        # 真实姓名
        driver.find_element_by_id('realname').send_keys('user%d'%i)

        # 性别
        driver.find_element_by_id( 'genderm' if i%2==0  else 'genderf').click()

        # 部门
        select = driver.find_element_by_id('dept')
        depts = Select(select)
        depts.select_by_index(random.randint(1,6)) # 根据下标进行选择，下标从0开始

        # 角色
        select = driver.find_element_by_id('role')
        roles = Select(select)
        roles.select_by_index(random.randint(1,16))

        # 密码
        driver.find_element_by_id('password1').send_keys('123456')

        # 密码
        driver.find_element_by_id('password2').send_keys('123456')

        # 邮箱
        driver.find_element_by_id('email').send_keys('user%d@163.com'%i)

        # 保存
        driver.find_element_by_id('submit').click()
        # 针对 NoSuchWindow问题
        sleep(2)

        # 跳转到最后一页
        driver.find_element_by_id('_pageID').send_keys('10000')
        driver.find_element_by_id('goto').click()
        sleep(2)

        # 获取最后一行的真实姓名
        realname = driver.find_elements_by_xpath('/html/body/div/div/div/div[2]/div/div/table/tbody/tr/td[2]')[-1].text
        # 断言
        assert realname == 'user%d'%i,'添加用户用例失败！'

except Exception as e:
    print(e)
finally:
    driver.close()



    